package com.snackshop.filter;

import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.snackshop.pojo.bo.UserBO;
import com.snackshop.pojo.vo.R;
import com.snackshop.pojo.vo.ResponseState;
import com.snackshop.service.impl.UserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("html/text;charset=utf-8");
        //获取请求链接
        String url = request.getRequestURL().toString();
        if(url.contains("login") || url.contains("register")){
            filterChain.doFilter(request,response);
            return;
        }
        //获取token
        String token = request.getHeader("X-Token");
        log.info(token);
        //判断
        if(token==null){
            R result = R.RESULT(ResponseState.NOTLOGIN);
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            response.getWriter().write(s);
            return;
        }
        //解析token
        String userPhone = JWTUtil.parseToken(token).getPayload("userPhone").toString();
        //用户验证
        UserBO userBO = (UserBO) userDetailsService.loadUserByUsername(userPhone);
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userBO,null,userBO.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
